<template>
	<view class="container">
		<view class="status-bar"></view>

		<view v-if="scanResult" class="scan-result-toast">
			{{ scanResult }}
			<view class="scan-again-tip">可继续扫描下一个</view>
		</view>
	</view>
</template>

<script>
	import {
		personnelScanCode,
		getVerification
	} from '../../api/index.js'

	const SCAN_INTERVAL = 1000 // 扫描间隔时间（毫秒）
	const SCAN_TYPES = [plus.barcode.QR, plus.barcode.EAN13, plus.barcode.EAN8, plus.barcode.CODE128]
	const BARCODE_STYLE = {
		top: '0',
		left: '0',
		width: '100%',
		height: '100%',
		scanbarColor: '#46B81E',
		position: 'static',
		frameColor: '#46B81E',
		vibrate: false
	}

	let barcode = null

	export default {
		data() {
			return {
				scanResult: '',
				isScanning: true,
				scanHistory: [],
				code: '',
				type: '',
				nativeViews: [],
				lastScanTime: 0, // 上次成功扫描时间戳
				pendingRequest: null // 当前未完成的请求
			}
		},

		onLoad(options) {
			Object.assign(this, options)
			// #ifdef APP-PLUS
			this.initAppScanner()
			// #endif
		},

		onBackPress() {
			this.cleanupResources()
			return false
		},

		onUnload() {
			this.cleanupResources()
		},

		methods: {
			// #ifdef APP-PLUS
			initAppScanner() {
				plus.navigator.setFullscreen(true)
				const webview = this.$scope.$getAppWebview()
				this.createBarcodeScanner(webview)
				this.createNativeControls(webview)
			},

			createBarcodeScanner(webview) {
				barcode = plus.barcode.create('scanner', SCAN_TYPES, BARCODE_STYLE)
				barcode.onmarked = this.handleScanResult
				webview.append(barcode)
				barcode.start()
			},

			createNativeControls(webview) {
				const backButton = new plus.nativeObj.View('backBtn', {
					top: '0px',
					left: '0px',
					height: '40px',
					width: '100%'
				}, [{
					tag: 'img',
					id: 'backIcon',
					src: '/static/left.png',
					position: {
						top: '2px',
						left: '3px',
						width: '35px',
						height: '35px'
					}
				}])

				backButton.addEventListener('click', this.backtoPage)
				webview.append(backButton)
				this.nativeViews.push(backButton)
			},
			// #endif

			async handleScanResult(type, result) {
				const now = Date.now()

				// 节流控制：1秒内不处理重复扫描
				if (now - this.lastScanTime < SCAN_INTERVAL) return

				// 防止重复处理
				if (!this.isScanning || this.pendingRequest) return

				this.isScanning = false
				this.lastScanTime = now

				try {
					// 取消当前扫描
					// #ifdef APP-PLUS
					barcode?.cancel()
					// #endif

					// 执行扫描处理
					const handler = this.type !== 'cancel' ?
						this.handleContainerScan :
						this.handleDefaultScan

					this.pendingRequest = handler(result)
					await this.pendingRequest
				} catch (error) {
					this.handleScanError(error)
				} finally {
					this.pendingRequest = null
					this.resetScanner()
				}
			},

			async handleContainerScan(result) {
				const res = await personnelScanCode({
					orderNo: result
				})
				console.log(res,140);
				if (!res.data) {
					throw new Error(res.message || '验证失败')
				}
				
				this.showScanSuccess(result)
				return res
			},

			async handleDefaultScan(result) {
				const res = await getVerification({
					verifyCode: result
				})

				if (!res.data) {
					throw new Error(res.message || '核销失败')
				}

				uni.navigateTo({
					url: `/pages/orderDetails/orderDetails?orderNo=${res.data}&orderType=1&verifyCode=${result}`
				})
				return res
			},

			showScanSuccess(result) {
				// console.log(result,165);
				uni.vibrateShort()
				this.scanResult = result
				this.scanHistory.push({
					code: result,
					type: this.type,
					timestamp: Date.now()
				})
				uni.showToast({
					title: '扫码成功',
					icon: 'success',
					duration: 2000
				})
				uni.reLaunch({
					url: '/pages/orderManageRider/orderManageRider'
				})	
			},

			handleScanError(error) {
				console.error('扫码错误:', error)
				uni.showToast({
					title: error || '扫码处理失败',
					icon: 'none',
					duration: 2000
				})
				this.scanResult = error.message
			},

			resetScanner() {
				setTimeout(() => {
					this.isScanning = true
					this.scanResult = ''
					// #ifdef APP-PLUS
					barcode?.start()
					// #endif
				}, SCAN_INTERVAL)
			},

			cleanupResources() {
				this.isScanning = false
				// #ifdef APP-PLUS
				plus.navigator.setFullscreen(false)
				barcode?.close()
				this.nativeViews.forEach(view => view.close())
				this.nativeViews = []
				// #endif
			},

			backtoPage() {
				uni.navigateBack()
			}
		}
	}
</script>

<style lang="scss" scoped>
	.container {
		position: relative;
		height: 100vh;
		overflow: hidden;
	}

	.status-bar {
		height: var(--status-bar-height);
		background: #FFFFFF;
	}

	.scan-result-toast {
		position: fixed;
		top: 40%;
		left: 50%;
		transform: translateX(-50%);
		background: rgba(0, 0, 0, 0.8);
		color: #FFFFFF;
		padding: 16rpx 32rpx;
		border-radius: 8rpx;
		text-align: center;
		z-index: 1000;
		max-width: 70%;
		font-size: 28rpx;
		animation: fadeIn 0.3s;

		.scan-again-tip {
			color: #CCCCCC;
			font-size: 24rpx;
			margin-top: 8rpx;
		}
	}

	@keyframes fadeIn {
		from {
			opacity: 0;
			transform: translate(-50%, -20px);
		}

		to {
			opacity: 1;
			transform: translate(-50%, 0);
		}
	}
</style>
